from const.charset_enum import Charset
from generator.gen import Gen
from dto.param import Param


class GenGBK(Gen):
    def __init__(self, param: Param = None):
        Gen.__init__(self, param)

    def check(self, c, charset):
        """
        About GBK Chinese:
          GBK/2 : 0xB0A1 ~ 0xF7FE (6763 chinese of GB2312 charset)
          GBK/3 : 0x8140 ~ 0xA0FE (6080 chinese of CJK(not all))
          GBK/4 : 0xAA40 ~ 0xB0A0 (8160 chinese of CJK and other chinese, 0xXX40 ~ 0xxxA0)

        GBK every region has 16*12(0~F * 0x40~0xF0) location, but every location of 0xXX7F, 0xXXFF is unused,
        so every region only has 190(192-2) location.

        :param c: current char
        :param charset: always GBK
        :return:  0x0000, if this char should not be handled
                  0xB0A1, if this char's location in [0xD7FA,0xD7FF](we need a placeholder)
                  c, return itself
        :brief:   Because the font library in Windows OS is encoded with Unicode almost, so we get
                  the font image through converting the other charset to Unicode
        """
        if c & 0xFF == 0x7F or c & 0xFF == 0xFF or c & 0xFF < 0x40:
            return 0x0000
        # convert to Unicode
        try:
            return ord(c.to_bytes(2, byteorder='big').decode(encoding=Charset.GBK.name.lower()))
        except UnicodeDecodeError:
            return ord(0xA1F5.to_bytes(2, byteorder='big').decode(encoding=Charset.GBK.name.lower()))
